"""
自定义错误处理视图
"""
from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
import logging

logger = logging.getLogger(__name__)

def custom_404(request, exception):
    """自定义404错误处理"""
    logger.warning(f"404错误: {request.path} - {exception}")

    # 如果是API请求，返回JSON响应
    if request.path.startswith('/api/'):
        return JsonResponse({
            'error': 'Not Found',
            'status': 404,
            'message': 'The requested resource was not found',
            'path': request.path
        }, status=404)

    # 否则返回HTML页面
    return render(request, 'errors/404.html', status=404)

def custom_500(request):
    """自定义500错误处理"""
    logger.error(f"500错误: {request.path}")

    # 如果是API请求，返回JSON响应
    if request.path.startswith('/api/'):
        return JsonResponse({
            'error': 'Internal Server Error',
            'status': 500,
            'message': 'An internal server error occurred',
            'path': request.path
        }, status=500)

    # 否则返回HTML页面
    return render(request, 'errors/500.html', status=500)

def custom_403(request, exception):
    """自定义403错误处理"""
    logger.warning(f"403错误: {request.path} - {request.user}")

    if request.path.startswith('/api/'):
        return JsonResponse({
            'error': 'Forbidden',
            'status': 403,
            'message': 'You do not have permission to access this resource',
            'path': request.path
        }, status=403)

    return render(request, 'errors/403.html', status=403)

def custom_400(request, exception):
    """自定义400错误处理"""
    logger.warning(f"400错误: {request.path} - {exception}")

    if request.path.startswith('/api/'):
        return JsonResponse({
            'error': 'Bad Request',
            'status': 400,
            'message': 'The request is invalid',
            'path': request.path
        }, status=400)

    return render(request, 'errors/400.html', status=400)